﻿using ECMS.AppService.Model.Requests;
using ECMS.AppService.Model.Responses;
using ECMS.Domain.Models;
using ECMS.Infrastructure.ClientData;
using ECMS.Infrastructure.Domain;
using ECMS.Infrastructure.Extensions;
using ECMS.Infrastructure.Messaging;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ECMS.AppService.Implements
{
    public partial class PostService
    {
        /// <summary>
        /// 用户所有帖子
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<Page<PostResponse>>> AllPostPageByUserAsync(GetPostPagesRequest request)
        {
            //获取最新发布的帖子
            var response = new ApiResult<Page<PostResponse>>();
            try
            {
                if (request == null)
                    throw new ArgumentNullException(nameof(request));

                // 读取数据
                var result = await Query()
                    //.HasWhere(request.Type, p => p.Type == "")
                    .HasWhere(request.AppUserId, p => p.AppUserId == request.AppUserId)
                    .Where(p => p.IsCheck && !p.IsDelete)
                    .OrderByDescending(p => p.CreateTime)
                    .ToPageAsync(request.PageIndex, request.PageSize);

                if (result.Items == null || result.Items.Count == 0)
                {
                    response.Message = "暂无数据.";
                    return response;
                }
                response.Success = true;
                response.Message = "获取成功.";

                // 转换数据
                response.Data = result.ToViewPage(p => new PostResponse
                {
                    Title = p.Title,
                    Content = p.Content,
                    CreateTime = p.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    IsCheck = p.IsCheck,
                    Type = p.Type,
                    IsShowQM = p.IsShowQM,
                    AppUserId = p.AppUserId,
                    Guid = p.Guid,
                    Id = p.Id,
                });
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }
        /// <summary>
        /// 推荐帖子
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<Page<PostResponse>>> AllPostPageAsync(GetPostPagesRequest request)
        {
            //获取最新发布的帖子
            var response = new ApiResult<Page<PostResponse>>();
            try
            {
                if (request == null)
                    throw new ArgumentNullException(nameof(request));

                // 读取数据
                var result = await Query()
                    .HasWhere(request.Type, p => p.Type == request.Type)
                    .Where(p => p.IsCheck && !p.IsDelete)
                    .OrderByDescending(p => p.CreateTime)
                    .ToPageAsync(request.PageIndex, request.PageSize);

                if (result.Items == null || result.Items.Count == 0)
                {
                    response.Message = "暂无数据.";
                    return response;
                }
                response.Success = true;
                response.Message = "获取成功.";

                // 转换数据
                response.Data = result.ToViewPage(p => new PostResponse
                {
                    Title = p.Title,
                    Content = p.Content,
                    CreateTime = p.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    IsCheck = p.IsCheck,
                    Type = p.Type,
                    IsShowQM = p.IsShowQM,
                    AppUserId = p.AppUserId,
                    Guid = p.Guid,
                    Id = p.Id,
                });
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<string>> DeletePostAsync(GuidRequest guid)
        {
            var response = new ApiResult<string>();
            try
            {
                if (guid == null)
                    throw new ArgumentNullException(nameof(guid));

                // 物理删除
                Delete(p => p.Guid == guid.Guid);

                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "删除成功." : "删除失败.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }
        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public async Task<ApiResult<PostResponse>> PostDetailAsync(GuidRequest request)
        {
            var response = new ApiResult<PostResponse>();
            try
            {
                if (request == null)
                    throw new ArgumentNullException(nameof(request));
                Forum entity = await Query().FirstOrDefaultAsync(p => p.Guid == request.Guid && p.IsCheck) ?? new Forum();

                response.Data = new PostResponse
                {
                    AppUserId = entity.AppUserId,
                    Content = entity.Content,
                    CreateTime = entity.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    Title = entity.Title,
                    Type = entity.Type,
                    Guid = entity.Guid,
                    Id = entity.Id
                };
            }
            catch (Exception e)
            {
                throw;
            }
            return response;
        }
        /// <summary>
        /// 发帖
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<SaveResponse>> PostingAsync(PostRequest model)
        {
            var response = new ApiResult<SaveResponse>();
            try
            {
                if (model == null)
                    throw new ArgumentNullException(nameof(model));
                Forum entity;
                if (model.Guid == null)
                {
                    entity = new Forum
                    {
                        Content = model.Content,
                        Title = model.Title,
                        Type = model.Type,
                        AppUserId = model.AppUserId,
                    };
                    await _unitofwork.RegisterNewAsync(entity);
                }
                else
                {
                    entity = await Query().FirstOrDefaultAsync(p => p.Guid == model.Guid);
                    if (entity == null)
                    {
                        response.Message = "找不到要修改的数据.";
                        return response;
                    }
                    entity.Content = model.Content;
                    entity.Title = model.Title;
                    entity.LastChangeTime = DateTime.Now;

                    _unitofwork.RegisterDirty(entity);
                }

                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "保存成功." : "保存失败.";
                response.Data = new SaveResponse
                {
                    Guid = entity.Guid,
                    Id = entity.Id
                };
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }


        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Task<ApiResult<PostResponse>> CheckPostAsync(PostRequest request)
        {
            throw new NotImplementedException();
        }


    }

    public partial class ReplyService
    {
        /// <summary>
        /// 获取评论
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<Page<ReplyResponse>>> AllReplyPageAsync(GetReplyPagesRequest request)
        {
            var response = new ApiResult<Page<ReplyResponse>>();
            try
            {
                if (request == null)
                    throw new ArgumentNullException(nameof(request));

                var result = await Query().HasWhere(request.ForumId, p => p.ForumId == request.ForumId)
                    .Where(p =>  !p.IsDelete)
                    .OrderByDescending(p => p.CreateTime)
                    .ToPageAsync(request.PageIndex, request.PageSize);
                
                response.Success = true;
                response.Message = "获取成功";
                // 转换数据
                response.Data = result.ToViewPage(p => new ReplyResponse
                {
                    Content = p.Content,
                    CreateTime = p.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    AppUserId = p.AppUserId,
                    Guid = p.Guid,
                    Id = p.Id,
                });

            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }
        /// <summary>
        /// 发布评论
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<SaveResponse>> CommentAsync(ReplyRequest request)
        {
            var response = new ApiResult<SaveResponse>();
            try
            {
                if (request == null)
                    throw new ArgumentNullException(nameof(request));
                Reply entity;
                if (request.Guid == null)
                {
                    entity = new Reply
                    {
                        Content = request.Content,
                        ForumId = request.ForumId,
                        AppUserId = request.AppUserId,
                    };
                    await _unitofwork.RegisterNewAsync(entity);
                }
                else
                {
                    entity = await Query().FirstOrDefaultAsync(p => p.Guid == request.Guid);
                    if (entity == null)
                    {
                        response.Message = "找不到要修改的数据.";
                        return response;
                    }
                    entity.Content = request.Content;
                    entity.LastChangeTime = DateTime.Now;
                    _unitofwork.RegisterDirty(entity);
                }

                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "保存成功." : "保存失败.";
                response.Data = new SaveResponse
                {
                    Guid = entity.Guid,
                    Id = entity.Id
                };
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }
        /// <summary>
        /// 删除评论
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<string>> DeleteReplyAsync(GuidRequest request)
        {
            var response = new ApiResult<string>();
            try
            {
                if (request == null)
                    throw new ArgumentNullException(nameof(request.Guid));

                // 物理删除
                Delete(p => p.Guid == request.Guid);

                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "删除成功." : "删除失败.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }
        /// <summary>
        /// 获取用户评论
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<Page<ReplyResponse>>> AllReplyPageByUserAsync(GetReplyPagesRequest request)
        {
            throw new NotImplementedException();
        }

        public async Task<ApiResult<ReplyResponse>> AllReplyCountAsync(ReplyRequest request)
        {
            var response = new ApiResult<ReplyResponse>();
            try
            {
                if (request == null)
                    throw new ArgumentNullException(nameof(request));

                var result = await Query().HasWhere(request.ForumId, p => p.ForumId == request.ForumId).CountAsync();

                response.Success = true;
                response.Message = "获取成功";
                response.Data = new ReplyResponse
                {
                    Count = result,
                    ForumId = request.ForumId
                };

            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }
    }

    public partial class LikeService
    {
        /// <summary>
        /// 帖子点赞OR取消
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<SaveResponse>> LikePostOrNotAsync(LikeRequest request)
        {
            var response = new ApiResult<SaveResponse>();
            try
            {
                if (request == null)
                    throw new ArgumentNullException(nameof(request));
                Like entity = await Query().FirstOrDefaultAsync(p => p.ForumId == request.ForumId && p.AppUserId == request.AppUserId);
                if (entity == null)
                {
                    entity = new Like
                    {
                        ForumId = request.ForumId,
                        AppUserId = request.AppUserId,
                        Status = request.Status
                    };
                    await _unitofwork.RegisterNewAsync(entity);
                }
                else
                {
                    entity.Status = request.Status;
                    _unitofwork.RegisterDirty(entity);
                }
                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "保存成功." : "保存失败.";
                response.Data = new SaveResponse
                {
                    Guid = entity.Guid,
                    Id = entity.Id
                };
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }

        /// <summary>
        /// 获取帖子点赞量 和 是否点赞
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<LikeResponse>>> AllLikeByPostAsync(LikeRequest request)
        {
            var response = new ApiResult<List<LikeResponse>>();
            try
            {
                if (request == null)
                    throw new ArgumentNullException(nameof(request));

                var result = await Query().HasWhere(request.ForumId, p => p.ForumId == request.ForumId).ToListAsync();

                List<LikeResponse> likes = new List<LikeResponse>();
                if (result.Count > 0)
                {
                    result.ForEach(p => likes.Add(new LikeResponse
                    {
                        AppUserId = p.AppUserId,
                        ForumId = p.ForumId,
                        Status = p.Status
                    }));
                }
                response.Success = true;
                response.Message = "获取成功";
                response.Data = likes;

            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }

        /// <summary>
        /// 获取评论点赞量 和 是否点赞
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Task<ApiResult<SaveResponse>> LikeReplyOrNotAsync(LikeRequest request)
        {
            throw new NotImplementedException();
        }
    }

    public partial class ViewService
    {
        public async Task<ApiResult<ViewResponse>> ViewPostCountAsync(ViewRequest request)
        {
            var response = new ApiResult<ViewResponse>();
            try
            {
                if (request == null)
                    throw new ArgumentNullException(nameof(request));

                var result = await Query().HasWhere(request.ForumId, p => p.ForumId == request.ForumId).Select(p => p.ClickNumber).FirstOrDefaultAsync();

                response.Success = true;
                response.Message = "获取成功";
                response.Data = new ViewResponse
                {
                    Count = result,
                    ForumId = request.ForumId
                };

            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }

    }
}